package cn.yunhe.dao;

import cn.yunhe.entity.Dept;
import cn.yunhe.entity.Emp;
import cn.yunhe.entity.Page;
import org.hibernate.*;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

@Repository("empDao")
public class EmpDaoImpl extends HibernateTemplate implements EmpDao {
    @Resource
    private SessionFactory sessionFactory;



    @Override
    public List<Emp> getAllEmp() {
        return find("from Emp");
    }

    @Override
    public List<Emp> searchEmp(final Page pages) {
        List list = executeFind(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(Emp.class);
               if(pages != null){
                   if (pages.getPageStart()>=0 && pages.getPageSize()>0){
                     criteria.setFirstResult(pages.getPageStart()).setMaxResults(pages.getPageSize());
                   }
               }
               return criteria.list();
            }
        });
        return list;
    }

    @Override
    public void addEmp(Emp emp) {

    }

    @Override
    public void updateEmp(Emp emp) {
       update(emp);
    }

    @Override
    public void delEmp(Emp emp) {
       delete(emp);
    }

    @Override
    public Emp getEmpById(int Id) {
        return get(Emp.class,Id);
    }

    @Override
    public Integer  getCounts() {
        String hql ="select count(e) from Emp e";
        return Integer.parseInt(String.valueOf(find(hql).get(0)));
    }

    @Override
    public List<Dept> getAllDept() {
        return find("from Dept");
    }


    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}